package me.seawenc.db.migration.helper;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * 封装得最简单日志工具类
 */
public class LogDataxHelper {
    private static final Logger logger = LogManager.getLogger(LogDataxHelper.class);
    private BufferedWriter writer;
    String logFilePath;
    public LogDataxHelper(String logFilePath) throws IOException {
        this.logFilePath=logFilePath;
        File file = new File(logFilePath);
        file.getParentFile().mkdirs();
        if(!file.exists()){
            file.createNewFile();
        }
        writer = new BufferedWriter(new FileWriter(logFilePath));
    }

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
    public void info(String msg){
        if(Optionalx.isPresent(msg)){
            writeToFile("\u001B[32m INFO \u001B[0m",msg);
        }
    }

    public void error(String msg){
        if(Optionalx.isPresent(msg)){
            writeToFile("\u001B[31m ERROR \u001B[0m",msg);
        }
    }

    private void writeToFile(String level,String msg){
        String now = LocalDateTime.now().format(formatter);
        String format = String.format("%s %s %s \n", now, level, msg);
        try{
            writer.write(format);
            writer.flush();
        } catch (IOException e) {
            logger.error("写入日志文件失败:"+logFilePath+",msg:"+msg+",error:"+e.getMessage());
        }
    }

    public void closeLogFile(){
        if(writer!=null){
            try {
                // 等待完在
                Thread.sleep(200);
                writer.flush();
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}
